package com.netdisk.service.impl;

import com.netdisk.Domain.FileBean;
import com.netdisk.Domain.User;
import com.netdisk.component.FileDealCode;
import com.netdisk.service.HDFSService;
import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;


@Slf4j
@Service
public class HDFSServiceImpl implements HDFSService {
    private static final int bufferSize = 1024 * 1024 * 64;

    @Autowired
    private FileSystem fileSystem;

    @Autowired
    FileDealCode fileDealCode = new FileDealCode();

    @Override
    public boolean makeFolder(String path) {
        boolean target = false;
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (existFile(path)) {
            return true;
        }
        Path src = new Path(path);
        try {
            target = fileSystem.mkdirs(src);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return target;
    }

    @Override
    public boolean existFile(String path) {
        if (StringUtils.isEmpty(path)){
            return false;
        }
        Path src = new Path(path);
        try {
            return fileSystem.exists(src);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return false;
    }

    @Override
    public List<FileBean> listFileByType(Integer Type, String path, HttpServletRequest request) {
        if (StringUtils.isEmpty(path)) {
            return Collections.emptyList();
        }
        if (!existFile(path)) {
            return Collections.emptyList();
        }
        List<FileBean> list = new ArrayList<>();
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String username = user.getUsername();
        String telephone = user.getTelephone();
        path = "/" + telephone + path;
        session.setAttribute("filePath",path);
        Path src = new Path(path);
        try {
            RemoteIterator<LocatedFileStatus> fileIterator = fileSystem.listFiles(src, true);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (fileIterator.hasNext()) {
                LocatedFileStatus file = fileIterator.next();
                String fileName = file.getPath().getName();
                int position = fileName.lastIndexOf(".");
                String suffix = fileName.substring(position+1);
                int storageType = fileDealCode.judgeType(suffix);
                if(storageType == Type){
                    FileBean fileBean = new FileBean();
                    fileBean.setUsername(username);
                    fileBean.setUserFileId(fileName);
                    fileBean.setFileName(fileName.substring(0,position));
                    String filePath = file.getPath().toString();
                    //剪切路径
                    String shortFilePath = filePath.substring(filePath.indexOf(telephone)-1);
                    fileBean.setFilePath(shortFilePath.substring(shortFilePath.indexOf(telephone)+telephone.length()));
                    fileBean.setUserFileId(shortFilePath);
                    fileBean.setFileSize(file.getLen());
                    fileBean.setIsDir(0);
                    //可能有问题
                    fileBean.setModifyTime(format.format(file.getModificationTime()));
                    fileBean.setExtendName(suffix);
                    fileBean.setStorageType(storageType);
                    list.add(fileBean);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return list;
    }

    @Override
    public List<FileBean> getListFile(String path,HttpServletRequest request) throws IOException {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String telephone = user.getTelephone();
        String username = user.getUsername();
        //保存当前路径
        String filePath = "/" + telephone + path;
        session.setAttribute("filePath",filePath);
        List<FileBean> list = new ArrayList<>();
        FileStatus[] files = fileSystem.listStatus(new Path(filePath));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < files.length ; i++) {//循环遍历文件
            FileStatus file = files[i];
            FileBean fileBean = new FileBean();
            String fileName = file.getPath().getName();
            fileBean.setUsername(username);
            String longFilePath = file.getPath().toString();
            String shortFilePath = longFilePath.substring(longFilePath.indexOf(telephone)-1);
            if(file.isDirectory()){
                fileBean.setFileName(fileName);

                fileBean.setFilePath(path);
                fileBean.setUserFileId(shortFilePath);

                fileBean.setFileSize(file.getLen());
                fileBean.setIsDir(1);
                fileBean.setUserFileId(fileName);
                //可能有问题
                fileBean.setModifyTime(format.format(file.getModificationTime()));

            }else{//文件
                int position = fileName.lastIndexOf(".");
                String suffix = fileName.substring(position+1);
                fileBean.setFileName(fileName.substring(0,position));

                fileBean.setFilePath(shortFilePath.substring(shortFilePath.indexOf(telephone)+telephone.length()));

                fileBean.setUserFileId(shortFilePath);

                fileBean.setFileSize(file.getLen());
                fileBean.setIsDir(0);
                fileBean.setUserFileId(fileName);
                //可能有问题
                fileBean.setModifyTime(format.format(file.getModificationTime()));
                fileBean.setExtendName(suffix);
                fileBean.setStorageType(fileDealCode.judgeType(suffix));
            }
            list.add(fileBean);
        }
        list.sort((a,b)->{
            if(a.getIsDir() == 1){
                return -1;
            }else{
                return 1;
            }
        });
        return list;
    }

    @Override
    public boolean renameFile(String oldName, String newName) {
        boolean target = false;
        if (StringUtils.isEmpty(oldName) || StringUtils.isEmpty(newName)) {
            return false;
        }
        Path oldPath = new Path(oldName);
        Path newPath = new Path(newName);
        try {
            target = fileSystem.rename(oldPath, newPath);
        } catch (IOException e) {
            log.error(e.getMessage());
        }

        return target;
    }

    @Override
    public boolean deleteFile(String path) {
        boolean target = false;
        if (StringUtils.isEmpty(path)) {
            return false;
        }
        if (!existFile(path)) {
            return false;
        }
        Path src = new Path(path);
        try {

            target = fileSystem.delete(src,true);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return target;
    }


    @Override
    public  List<FileBean> getListByName(HttpServletRequest request,String fileName){
        List<FileBean> list = new ArrayList<>();
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String telephone = user.getTelephone();
        String username = user.getUsername();
        String path = "/" + telephone + "/";
        Path src = new Path(path);
        try {
            RemoteIterator<LocatedFileStatus> fileIterator = fileSystem.listFiles(src, true);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            while (fileIterator.hasNext()) {
                LocatedFileStatus file = fileIterator.next();
                String fileName1 = file.getPath().getName();
                if(fileName1.contains(fileName)){
                    int position = fileName1.lastIndexOf(".");
                    String suffix = fileName1.substring(position+1);
                    int storageType = fileDealCode.judgeType(suffix);
                    FileBean fileBean = new FileBean();
                    fileBean.setUsername(username);
                    fileBean.setFileName(fileName1.substring(0,position));
                    String filePath = file.getPath().toString();
                    //剪切路径
                    String shortFilePath = filePath.substring(filePath.indexOf(telephone)-1);
                    fileBean.setFilePath(shortFilePath.substring(shortFilePath.indexOf(telephone)+telephone.length()));
                    fileBean.setUserFileId(shortFilePath);
                    fileBean.setFileSize(file.getLen());
                    fileBean.setIsDir(0);
                    fileBean.setModifyTime(format.format(file.getModificationTime()));
                    fileBean.setExtendName(suffix);
                    fileBean.setStorageType(storageType);
                    list.add(fileBean);
                }
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return list;
    }

    @Override
    public Long getSize(String src) throws IOException {
        Path srcPath = new Path(src);
        FileStatus[] status = fileSystem.globStatus(new Path(src));
        long totalSize = 0L;
        if (status==null || status.length==0) {
           return 0L;
        }
        for(int i=0; i<status.length; i++) {
            totalSize = fileSystem.getContentSummary(status[i].getPath()).getLength();
        }
        return totalSize;
    }
}
